﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Ivory;
using Microsoft.Xna.Framework.Graphics;
using Jitter;
using Jitter.Collision;
using Crystal.Mapping;
using Ivory.GUI;
using Crystal.libs;

namespace Crystal.Structure
{
    public class BarvaLevel : GameScreen
    {
        public static readonly string Key = "##:BARVALEVEL:##";
        public static string LevelFile = null;

        //Fields
        private LevelMap _BarvaLevelMap;
        private GUI _LevelInterface;

        //cTor
        public BarvaLevel(Game game)
            : base(game)
        {

        }

        //Methods
        private void LoadGUI()
        {

        }
        
        public override void RenderGame(SpriteBatch batch, GameTime time)
        {
            _BarvaLevelMap.DrawMap();
        }    
        public override void UpdateGame(GameTime time, InputControl input)
        {
            //_BarvaLevelMap.Update(time);
        }
        
        public override void RenderUI(SpriteBatch batch, GameTime time)
        {
            batch.Begin();
            _LevelInterface.DrawGUI(batch, time);
            batch.End();
        }
        public override void UpdateUI(GameTime time, InputControl input)
        {
            _LevelInterface.UpdateGUI(input, time);
        }

        public override bool PreloadAssets()
        {
            //Things to be loaded when the game startups, not for each level
            //E.g. GameMenus / Load Screen!!!

            return true;
        }
        public override bool LoadData()
        {
            //Assign Globals
            Crystal.Globals.GameWorld = new World(new CollisionSystemSAP());
            Crystal.Globals.GameWorld.Gravity = new Jitter.LinearMath.JVector(0);

            Crystal.Globals.GameCamera = new Crystal.Libs.GameCamera(Game);
            Crystal.Globals.GlobalDebugRenderer = new Crystal.Libs.DebugDrawer(Game);
            Crystal.Globals.GlobalDebugRenderer.Initialize();
                        
            /* 
             * Load in the LevelFile String which should have been set, if its null, throw an error
             */
            if (string.IsNullOrEmpty(BarvaLevel.LevelFile))
                throw new CrystalFrameworkError(Errors.NoGameFileSpecified);
            
            //Game Data
            Exception e;
            LevelSerializableDataStructure ds = LevelSerializableDataStructure.Deserialize(BarvaLevel.LevelFile, out e);

            if (e != null)
            {
                //Errors
                return false;
            }


            _BarvaLevelMap = ds.Levelmap;

            //GUI
            _LevelInterface = new GUI();
            LoadGUI();

            return true;
        }

        
    }
}
